package com.project.nimsen.web.pub.tag;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import com.project.nimsen.constant.NimsenConstant;
import com.project.nimsen.dto.UrlinfoDto;
import com.project.nimsen.service.IUrlinfoService;

import freemarker.core.Environment;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;
/**
 * 用于得url集合信息
 * */
@Component("nimsen_urls")
public class UrlsTag extends BaseTag {
	@Resource
	IUrlinfoService urlinfoService;
	/**
	 * @param id id编号，必须与urltype类型相对应
	 * @param urltype 如果值为archivesurl则返对应的编号为id文章的url集合
	 * 				,默认为archivesurl
	 * @param num 查询附件的前几个，默认查询全部信息
	 * @param order ASC为升序，DESC为降序，默认为ASC
	 * 
	 * @return urls 向页面输出集合的名称
	 * */
	protected void exec(Environment env, Map params, TemplateModel[] loopVars,
			TemplateDirectiveBody body) throws TemplateException, IOException {
		//URL类型
		String urltype = getParam("urltype");
		if(StringUtils.isBlank(urltype))
			urltype = NimsenConstant.ARCHIVES_URL_LIST;
		//编号
		String id = getParam("id");
		if(StringUtils.isBlank(id)){
			String curid = getAttr("archid");
			//如果当前文章编号也为空则返回
			if(StringUtils.isBlank(curid))
				return;
			id = curid;
		}
		UrlinfoDto dto = new UrlinfoDto();
		dto.setUrloutable(urltype);
		dto.setUrloutid(id);
		//查询前几个url信息
		Integer num = getIntegerParam("num");
		if(num!=null&&num>0)
			dto.setNum(num);
		String order = getParam("order");
		if("DESC".equals(order))
			dto.setOrderType("DESC");
		else
			dto.setOrderType("ASC");
		try {
			//得到要查询的url集合
			List<Map<String, Object>> list = urlinfoService.findTagUrlByDto(dto);
			if(CollectionUtils.isNotEmpty(list)){
				outVariable("urls", list);
				body.render(env.getOut());
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
